<?php
session_start(); 
include('system/connect.php');

function birthday ($birthday){
    list($year,$month,$day) = explode("-",$birthday);
    $year_diff  = date("Y") - $year;
    $month_diff = date("m") - $month;
    $day_diff   = date("d") - $day;
    if ($day_diff < 0 || $month_diff < 0)
      $year_diff--;
    return $year_diff;
}

$my_id = $_SESSION['my_id'];
$sql = "SELECT
        sf_guard_user.id,
        sf_guard_user.first_name,
        sf_guard_user.phone,
        sf_guard_user.gender,
        sf_guard_user.partner_id,
        sf_guard_user.account        
        FROM
        sf_guard_user
        WHERE
        sf_guard_user.id = '$my_id'";
$result = mysql_query($sql);
while ($row = mysql_fetch_assoc($result)) {
    $my_info = $row;
}  
if ($my_info['gender'] == 'm') {
    $gender = 'w';
    if ($my_info['account'] <= 0) {
        $err = 'go away!';           
        header('Cache-Control: no-cache, must-revalidate');
        header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
        header('Content-type: application/json');
        echo (json_encode($err));
        exit();
    }
    
} else {
    $gender = 'm';
}

                          
$online = array();
$chating = array();

//Get online users
$sql = "SELECT
        sf_guard_user.id,
        sf_guard_user.first_name,
        sf_guard_user.username,
        sf_guard_user.nickname,
        sf_guard_user.phone,
        sf_guard_user.gender,
        sf_guard_user.photo,
        sf_guard_user.age,
        sf_guard_user.is_marital,
        sf_guard_user.birthday,
        sf_guard_user.city,
        sf_guard_user.country,
        sf_guard_user.eye_color,
        sf_guard_user.height,
        sf_guard_user.ves,
        sf_guard_user.hair_color,
        sf_guard_user.hair_type,
        chat2_chanels.girl_src,
        sf_guard_user.hair_lenght
        FROM
        sf_guard_user             
        Left Join chat2_chanels ON sf_guard_user.id = chat2_chanels.user_id
        WHERE            
        sf_guard_user.is_online<>0 and sf_guard_user.is_partner=0 and sf_guard_user.is_super_admin=0 and sf_guard_user.id<>$my_id and sf_guard_user.gender = '".$gender."'
        ORDER BY sf_guard_user.last_login DESC" ;  
$rez = mysql_query($sql);  
while ($row = mysql_fetch_assoc($rez)) {  
    if ((!empty($row['first_name'])) && (strlen($row['first_name']) >= 3)) {
        $name = $row['first_name'];
    } elseif (!empty($row['nickname'])) {
        $name = $row['nickname'];        
    } else {
        $name = $row['username'];
    }
    if (!empty($row['girl_src'])) {
        $have_video = 1;
    } else {
        $have_video = 0;
    }
    $info = '';
    //1978-11-04       
    if (!empty($row['birthday'])){                      
        $age = birthday($row['birthday']);       
    } else {
        $age = '??';
    }
    if ($row['gender'] == 'm') {    
        $info = 'Возраст: '.$age.' лет<br />';
        if (!empty($row['is_marital'])) {      
            $info .= 'Статус: '.$row['is_marital'].'<br />';
        }   
        if (!empty($row['city'])) {
            $info .= ''.$row['city'];
        }
        if (!empty($row['country'])) {
            $info .= ' '.$row['country'];
        }
    } else {
        $info = $age.' years old';           
        if (!empty($row['is_marital'])) {
            $info .= '<br />Status: '.$row['is_marital'];
        }   
        if (!empty($row['eye_color'])) {
            $info .= '<br />Eyes: '.$row['eye_color'];
        }
        if (!empty($row['hair_color'])) {
            $info .= '<br />Hair: '.$row['hair_color'];
        }
        if (!empty($row['height'])) {
            $info .= '<br />Height: '.$row['height'].'cm';
        }  
        if (!empty($row['ves'])) {
            $info .= '<br />Weight: '.$row['ves'].'kg';
        }    
    }
    
    $online[] = array(  'id' => $row['id'],
                        'name' => $name,
                        'ava' => $row['photo'],
                       'age' => $age,
                        'gender' => $row['gender'],
                     //   'is_marital' => $row['is_marital'],
                     //   'eye_color' => $row['eye_color'],
                    //    'hair_color' => $row['hair_color'],
                        'video' => $have_video,
                        'info' => $info                       
    );   
} 

//get active rooms
$sql = "SELECT chat2_room.id,chat2_room.is_active,chat2_room.with_video,chat2_room.time FROM chat2_room
Inner Join chat2_room_users ON chat2_room_users.room_id = chat2_room.id
WHERE chat2_room_users.user_id = '$my_id' AND chat2_room.is_active <> '$my_id'";   
$result = mysql_query($sql);
$return = array();
$room = array();   
$oponents = array();  
while ($row = mysql_fetch_assoc($result)) {
    $messages = array(); 
    $sql = "SELECT
            sf_guard_user.first_name,
            sf_guard_user.id as user_id,
            sf_guard_user.photo,
            sf_guard_user.partner_id,
            chat2_room_users.id,
            chat2_room_users.aproved,
            chat2_room_users.last_active,
            chat2_room.id,       
            chat2_chanels.girl_src 
            FROM
            sf_guard_user
            Inner Join chat2_room_users ON chat2_room_users.user_id = sf_guard_user.id
            Inner Join chat2_room ON chat2_room_users.room_id = chat2_room.id          
            Left Join chat2_chanels ON chat2_room_users.user_id = chat2_chanels.user_id 
            WHERE
            chat2_room_users.room_id = '".$row['id']."'";   
    $room_res = mysql_query($sql); 
    $room_id = $row['id']; 
    $chat_payed = 0; 
    $op_partner_id = 0;
    $last_active = time();
    $users = array();     
    while ($r = mysql_fetch_assoc($room_res)) { 
        if ((time() - $r['last_active']) > 10) {
            $status = 0;
        } else {              
            $status = 1;  
        }
        
        if ((time() - $r['last_active']) > 360) {
       //     print_r('oollddd');
             mysql_query("delete from `chat2_room` where `chat2_room`.`id` = '".$row['id']."'");
             mysql_query("delete from `chat2_room_users` where `chat2_room_users`.`room_id` = '".$row['id']."'");
        }            
        if (!empty($r['girl_src'])) {
            $have_video = 1;
        } else {
            $have_video = 0;
        }  
        if ($r['user_id'] != $my_id) {
            $op_id = $r['user_id'];    
            $op_partner_id = $r['partner_id'];  
            //print_r($op_id);
        } else {
            if (((time() - $r['last_active']) < 120) && ($r['aproved'] == '1')) {
                $chat_payed = 1;
                $last_active = $r['last_active'];
            }
            //Now my_id circle
        }
        $users[] = array('id' => $r['user_id'],'name' => $r['first_name'],'ava' => $r['photo'],'status' => $status,'have_video' => $have_video);
    }   
    //print_r($row);
    if ($row['is_active'] != 1) {      
        mysql_query("delete from `chat2_room` where `chat2_room`.`id` = '$room_id'");
        mysql_query("delete from `chat2_room_users` where `chat2_room_users`.`room_id` = '$room_id'");
    }
    $sql = "SELECT
            chat2_message.room_id,
            chat2_message.id,
            chat2_message.user_id,
            chat2_message.content,
            sf_guard_user.first_name,
            sf_guard_user.gender
            FROM
            chat2_message               
            Inner Join sf_guard_user ON chat2_message.user_id = sf_guard_user.id      
            WHERE
            chat2_message.`read` = '0' AND chat2_message.room_id = '$room_id' AND chat2_message.user_id <> '$my_id'
            ORDER BY
            chat2_message.created_at ASC";
    $mess = mysql_query($sql);        
    while ($rm = mysql_fetch_assoc($mess)) { 
       $messages[] = array('text' => $rm['content'],'name' => $rm['first_name'],'gender' => $rm['gender']); 
    }
    $sql = "UPDATE 
            `chat2_message` 
            SET `chat2_message`.`read` = '1' 
            WHERE `chat2_message`.`read` = '0' AND `chat2_message`.`room_id` = '$room_id' AND `chat2_message`.`user_id` <> '$my_id'";
    mysql_query($sql);   
    
                                                   
    if (($chat_payed == 1) && ($my_info['gender'] == 'm')) {   
        $time = time(); 
        $mysqldate = date( 'Y-m-d H:i:s', $time );        
        $delta = time() - $last_active; 
        if ($delta < 20) {
            $cost = $chat_per_sec*$delta;  
            $sql = "update sf_guard_user set account=(account-$cost) where id = '$my_id'";
            mysql_query($sql);
            //print_r($delta);
            //print_r($cost);            
            $sql = "select * from payment where user_id = '$my_id' and room_id = '$room_id' and level_id = 18 limit 0,1";
            $logs = mysql_query($sql); 
            $log = array();       
            while ($l = mysql_fetch_assoc($logs)) { 
               $log[] = $l;
            }   
            if (!empty($log)) {     
                    $komis = '';         
                    if ($op_partner_id != 0) {  
                        $komis = ",komission=(komission+0.003*".$delta.")";
                    } 
                    $sql = "update payment set date_expire='$mysqldate',summa=summa+$cost".$komis." where user_id = '$my_id' and level_id = 18 and room_id = '$room_id'";
                  //  print_r($sql.'|');
                    mysql_query($sql);   
               } else {  
                    $komis = 0;                            
                    if ($op_partner_id != 0) { 
                        $komis = 0.003*$delta;
                    }               
                    $sql = "insert into payment (user_id,payment_id,room_id,created_at,level_id,partner_id,komission,summa) values ($my_id,$my_id,$room_id,'$mysqldate',18,'".$op_partner_id."',$komis,$cost)";  
                   //print_r($sql); 
                   mysql_query($sql);   
               }   
        } else {
            exit();
        }        
    }  
    
    if (($row['with_video'] != '0') && ($my_info['gender'] == 'm')) {
        //account
        $sql = "select * from payment where user_id = '$my_id' and room_id = '$room_id' and level_id = 17 limit 0,1";
        $logs = mysql_query($sql); 
        $log = array();       
        while ($l = mysql_fetch_assoc($logs)) { 
           $log[] = $l;
        }               
       //print_r($log);          
        //print_r($my_info['account']);              
        $time = time(); 
        $mysqldate = date( 'Y-m-d H:i:s', $time );   
        if ($my_info['account'] > 0) {   
            $delta = time() - $row['time']; 
            $cost = $per_sec*$delta;   
            //print_r($op_id.'|');   
            $user_sql = "SELECT
                    sf_guard_user.id,      
                    sf_guard_user.first_name,      
                    sf_guard_user.partner_id  
                    FROM
                    sf_guard_user
                    WHERE
                    sf_guard_user.id =  '$op_id'";
            $op_user = mysql_query($user_sql);
            while ($ur = mysql_fetch_assoc($op_user)) {
                $op_userdata = $ur;
            }    
                           
            $sql = "update sf_guard_user set account=(account-$cost) where id = '$my_id'";
            $my_info['account'] = $my_info['account'] - $cost;
            //print_r($sql."|");
            mysql_query($sql);    
            //print_r($log);                                                                                                                  
            $sql = "update chat2_room set time=$time where id = '$room_id'";
            mysql_query($sql);   
                            
            if (!empty($log)) {     
                $komis = '';         
                if (!empty($my_info['partner_id'])) {  
                    $komis = ",komission=(komission+0.004*".$delta.")";
                } 
                $sql = "update payment set date_expire='$mysqldate',summa=summa+$cost".$komis." where user_id = '$my_id' and room_id = '$room_id'";
               // print_r($sql.'|');
                mysql_query($sql);   
            } else {  
                $komis = 0;         
                if (!empty($my_info['partner_id'])) {  
                    $komis = 0.004*$delta;
                }               
                $sql = "insert into payment (user_id,payment_id,room_id,created_at,level_id,partner_id,komission,summa) values ($my_id,$my_id,$room_id,'$mysqldate',17,'".$op_userdata['partner_id']."',$komis,$cost)";  
               //print_r($sql); 
               mysql_query($sql);   
            }
        } else {
            $row['with_video'] = 0;                  
            $sql = "update chat2_room set with_video=0 where id = '$room_id'";
            mysql_query($sql);     
            $sql = "update sf_guard_user set account=0 where id = '$my_id'"; 
            mysql_query($sql);   
            $sql = "update chat2_video_log set time_end='$time',delta=time_end-time_start";
            mysql_query($sql);   
        }
        $sql = 'select ';
    }
    
    $room[] = array('id' => $room_id,'users' => $users,'status' => $row['is_active'],'with_video' => $row['with_video'],'messages' => $messages); 
    
}                     

$resp = array();

$resp['online'] = $online;
$resp['chating'] = $room;
$resp['money'] = $my_info['account'];


//update my activity
$timestamp = time();
$sql = "update `chat2_room_users` set `last_active`= '$timestamp' where `user_id` = '$my_id'";
mysql_query($sql);
$sql = "update `chat2_chanels` set `last_active`= '$timestamp' where `user_id` = '$my_id'";
mysql_query($sql);
$sql = "update `sf_guard_user` set `is_online`= '1' where `id` = '$my_id'";
mysql_query($sql);

/*
$sql = "delete from `chat2_room_users` where ($timestamp-`last_active`) > 60;";
mysql_query($sql);      
*/

header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Content-type: application/json');
echo (json_encode($resp));
?>